/**
 * 路由导航守卫
 * @function
 * @param {VueRouter} router 路由实例
 */

import NProgress from 'nprogress'
import {parse} from '../utils/url'
import { setToken, getToken } from '../helper/token';

import {LOGIN_PAGE} from '@/config'

// 进度自动递增20%
NProgress.inc(0.2)

export default function (router) {
  /**
   * 全局前置守卫
   */
  router.beforeEach((to, from, next) => {
    NProgress.start()
    let token = parse(window.location.href.split('?')[1]).token // 获取url上token
    if (token) {
      setToken(token)
      next()
    } else {
      if (getToken(token)) { // 获取缓存token
        next()
      } else {
        next(false)
        // console.log('redirect', LOGIN_PAGE)
        window.location.href = LOGIN_PAGE

      }
    }
  });
  
  /**
   * 全局后置守卫
   */
  router.afterEach((to, from) => {
    NProgress.done()
  })
  
}


